#!/usr/bin/env python3
"""
patch-tracking MCP Server

面向 patch-tracking 软件的 MCP Server，提供对 patch-tracking 服务管理的命令行操作封装。

MCP tools 列表：
- patch_tracking_service_restart: 重启 patch-tracking 服务
  用途：执行 systemctl restart patch-tracking.service 命令来重启服务
  参数：无
  返回结构：{"success": bool, "command": str, "exit_code": int, "stdout": str, "stderr": str}
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json

mcp = FastMCP("Patch-tracking MCP Server")

@mcp.tool()
def patch_tracking_service_restart() -> dict:
    """
    重启 patch-tracking 服务
    
    用途：执行 systemctl restart 命令来重启 patch-tracking.service
    参数：无
    返回 JSON 结构：
    {
        "success": bool,      # 命令是否成功执行（exit_code 为 0）
        "command": str,       # 实际执行的命令
        "exit_code": int,     # 命令的退出码
        "stdout": str,        # 命令的标准输出
        "stderr": str         # 命令的错误输出
    }
    """
    command = ["systemctl", "restart", "patch-tracking.service"]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command execution timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Command execution failed: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()